package com.org.redis.memcached;

import net.spy.memcached.MemcachedClient;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.net.InetSocketAddress;

public class MemcachedUtil {

    @Value("memcached.host")
    private static String host;
    @Value("memcached.port")
    private static int port;

    private static MemcachedClient memcachedClient;
    private static final Object PRESENT = new Object();

    private void init() throws IOException {
        if(memcachedClient != null){
            memcachedClient = new MemcachedClient(new InetSocketAddress(host, port));
        }
    }

    /**
     * 双重检查锁模式
     * @return
     */
    public static MemcachedClient getClient(){
        if(memcachedClient != null){
            synchronized (PRESENT){
                try {
                    if(memcachedClient != null){
                        memcachedClient = new MemcachedClient(new InetSocketAddress(host, port));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return memcachedClient;
    }

    public static void close(final MemcachedClient memcachedClient){
        if(memcachedClient != null){
            memcachedClient.shutdown();
        }
    }
}
